package eteam.aps.systemservice.bll;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import eteam.aps.common.QueryResult;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.systeminterface.model.dto.LogDto;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import eteam.aps.systeminterface.model.entity.LogEntity;
import eteam.aps.systeminterface.model.reqparam.QueryLogParam;
import eteam.aps.systemservice.dal.LogDal;
import eteam.aps.systemservice.model.mapper.ILogMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 日志相关业务
 */
@Service
public class LogBll {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogDal logDal;

    /**
     * 分页查询日志
     *
     * @param queryParam
     * @return
     */
    public QueryResult<LogEntity> queryPageList(QueryLogParam queryParam) throws Exception {
        IPage<LogEntity> page = new Page<LogEntity>(queryParam.getPageIndex(), queryParam.getPageSize());
        QueryWrapper<LogEntity> wrapper = new QueryWrapper<LogEntity>();
        if (StringUtils.isNotBlank(queryParam.getMenuid())) {
            wrapper.eq("FModuleId", queryParam.getMenuid());
        }
        if (StringUtils.isNotBlank(queryParam.getKeyword())) {
            wrapper.like("FDesc", queryParam.getKeyword());
        }
        if (StringUtils.isNotBlank(queryParam.getSortFields())) {
            wrapper.orderByDesc(queryParam.getSortFields());
        } else {
            wrapper.orderByDesc("FLogTime");
        }
        page = logDal.selectPageList(page, wrapper);
        QueryResult<LogEntity> result = new QueryResult<LogEntity>(Math.toIntExact(page.getTotal()), page.getRecords());
        return result;
    }

    /**
     * 创建日志
     *
     * @param moduleid:   模块ID
     * @param modulename: 模块名称
     * @param operkey:    操作Key
     * @param operName:   操作名称
     * @param dataid:     数据ID
     * @param desc:       描述
     */
    public void createLog(String moduleid, String modulename, String operkey, String operName, String dataid, String desc) {
        try {
            VerifyTokenDto tokenDto = Convert.convert(VerifyTokenDto.class, request.getAttribute("tokenInfo"));
            LogDto logDto = new LogDto();
            logDto.setFmoduleid(moduleid);
            logDto.setFmodulename(modulename);
            logDto.setFoper(operkey);
            logDto.setFopername(operName);
            logDto.setFdataid(dataid);
            logDto.setFdesc(desc);
            insertLog(tokenDto.getFuserid(), tokenDto.getFfullname(), logDto);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 创建日志
     *
     * @param logDto: 请求参数
     */
    public void createLog(LogDto logDto) {
        try {
            VerifyTokenDto tokenDto = Convert.convert(VerifyTokenDto.class, request.getAttribute("tokenInfo"));
            insertLog(tokenDto.getFuserid(), tokenDto.getFfullname(), logDto);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 创建日志
     *
     * @param tokenDto: 当前用户
     * @param logDto:   请求参数
     * @throws Exception
     */
    public void createLog(VerifyTokenDto tokenDto, LogDto logDto) throws Exception {
        insertLog(tokenDto.getFuserid(), tokenDto.getFfullname(), logDto);
    }

    /**
     * 根据ID删除
     *
     * @param id: Id
     * @throws Exception
     */
    public void deleteLog(String id) throws Exception {
        int count = logDal.deleteById(id);
        if (count < 1) {
            throw new BusinessException("删除日志失败");
        }
    }

    /**
     * 根据ID批量删除
     *
     * @param ids: Id集合
     * @throws Exception
     */
    public void deleteLog(List<String> ids) throws Exception {
        int count = logDal.deleteByIds(ids);
        if (count < 1) {
            throw new BusinessException("批量删除日志失败");
        }
    }

    /**
     * 创建日志
     *
     * @param userId:   用户ID
     * @param userName: 用户名称
     * @param logDto:   日志对象
     */
    private void insertLog(String userId, String userName, LogDto logDto) {
        String clientIp = ServletUtil.getClientIP(request);
        //String clientIp = ServletUtil.getClientIPByHeader(request);
        LogEntity logEntity = ILogMapper.INSTANCE.toEntity(logDto);
        logEntity.setFuserid(userId);
        logEntity.setFusername(userName);
        logEntity.setFlogtime(DateUtil.date());
        logEntity.setFipaddress(clientIp);
        int count = logDal.insertLog(logEntity);
        if (count < 1) {
            throw new BusinessException("创建日志失败");
        }
    }
}
